<script setup lang="ts">
import {onLoad} from "@dcloudio/uni-app";
import {ref} from "vue";
import {info} from '@/api/goods.ts'
import {baseUrl} from '@/api/request'
import {pageReceive} from '@/api/receiveaddress.ts'
import {save,total} from '@/api/shoppingcart.ts'
import {getWxPayInfo,saveOrder,closeOrder} from '@/api/order.ts'
import{pageComment} from '@/api/ordercomment.ts'
import loginDialog from '@/pages/personcenter/login.vue'

const currentGoodsId=ref()
onLoad((options)=>{
	currentGoodsId.value=options.id
	getInfo(options.id)
	getCartNum(options.id)
	getComment(options.id)
})
const queryParamsComment=ref({
	page:1,
	limit:10,
	goodsId:null,
	commentStatus:0
})
const comments=ref([])
const commenttotal=ref(0)
const getComment=(goodsId)=>{
	queryParamsComment.value.goodsId=goodsId;
	pageComment(queryParamsComment.value).then(res=>{
		comments.value=res.data.list
		commenttotal.value=res.data.total
		comments.value.forEach(item=>{
			if(item.commentPictures){
				item.commentPicturesFirst=item.commentPictures.split(',')[0]
			}
		})
	})
}
const getCartNum=(id)=>{
	total({"goodsId":id}).then(res=>{
		options.value[2].info=res.data
	})
}
const infoObj=ref()
const getInfo=(id)=>{
	info(id).then(res=>{
		infoObj.value=res.data
		infoObj.value.descHtml=infoObj.value.descHtml.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;border-radius:5px;"');
	})
}
const cover=ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg')
const detail=ref('<p><h2>多姿</h2></p>')
const options=ref([
	{
	      icon: 'shop',
	      text: '店铺',
	},
	{
      icon: 'chat',
      text: '客服'
    }, {
      icon: 'cart',
      text: '购物车',
      info: 0,
	  infoColor:"red"
    }])
const  buttonGroup=[{
      text: '加入购物车',
      backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
      color: '#fff'
    },
      {
        text: '立即购买',
        backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
        color: '#fff'
      }
    ]
const onClick=(e)=> {
  if (e.content.text == '购物车'){
	  uni.switchTab({
	    url:'/pages/chart/index'
	  })
  }else if (e.content.text == '客服'){
	  uni.navigateTo({
		 url:'/pages/message/detail?shopId='+infoObj.value.shopId
	  })
  }else if (e.content.text == '店铺'){
	  uni.navigateTo({
	    url:'/pages/shop/index?id='+infoObj.value.shopId
	  })
  }
}
const sumitText=ref()
const buttonClick=(e)=> {
  getDefaultAddress()
  if(e.content.text === '立即购买'){
	  sumitText.value='立即购买'
  }else if(e.content.text === '加入购物车'){
	  sumitText.value='加入购物车'
  }
  popup.value.open('bottom')
}
const popup=ref(false)
const change=(e)=> {
  console.log('当前模式：' + e.type + ',状态：' + e.show);
}
const quantity=ref(0)
const close=()=>{
  popup.value.close()
}
const goToReceivingAddress=()=>{
  uni.navigateTo({
    url:'/pages/receivingaddress/index'
  })
}
const currentIndex=ref(-1) 
const weightIds=ref([])
const sizesIds=ref([])
const colorClassicIds=ref([])
const productSpecificationsIds=ref([])
const selectButton=(id,index)=>{
	currentIndex.value=index
	weightIds.value.push(id)
}
const currentIndexSize=ref(-1) 
const selectButtonSize=(id,index)=>{
	currentIndexSize.value=index
	sizesIds.value.push(id)
}
const currentIndexColorClassic=ref(-1) 
const selectButtonColorClassic=(id,index)=>{
	currentIndexColorClassic.value=index
	colorClassicIds.value.push(id)
}
const toast=ref()
const sumitBtn=()=>{
	if(!uni.getStorageSync('token')){
		uni.setStorageSync('login',true)
		return
	}
	 productSpecificationsIds.value=[]
	if(sumitText.value === '立即购买'){
		// 仅作为示例，非真实参数信息。
		saveOrder({"goodsId":infoObj.value.id,"receivingAddressId":myaddress.value.id,
		"placeOrderQuantity":quantity.value,"placeOrderUnitPrice":infoObj.value.price,
		"productSpecificationsIds":productSpecificationsIds.value.join(',')}).then(ressave=>{
			if(ressave.code==200){
				getWxPayInfo({"amount":infoObj.value.price*quantity.value,"orderId":ressave.data}).then(res=>{
					// 仅作为示例，非真实参数信息。
					uni.requestPayment({
					    provider: 'wxpay',
						timeStamp: res.data.timeStamp,
						nonceStr: res.data.nonceStr,
						package: res.data.packageVal,
						signType: res.data.signType,
						paySign:  res.data.paySign,
						success: function (res) {
							console.log('success:' + JSON.stringify(res));
							popup.value.close()
						},
						fail: function (err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
				})
			}
		})
	}else if(sumitText.value === '加入购物车'){
		weightIds.value.forEach(item=>{
			productSpecificationsIds.value.push(item)
		})
		sizesIds.value.forEach(item=>{
			productSpecificationsIds.value.push(item)
		})
		colorClassicIds.value.forEach(item=>{
			productSpecificationsIds.value.push(item)
		})
		if(quantity.value == 0){
			uni.showToast({
				title:'数量不能为空'
			})
			return;
		}
		if(productSpecificationsIds.value.length == 0){
			uni.showToast({
				title:'规格不能为空'
			})
			return;
		}
		if(!myaddress.value){
			uni.showToast({
				title:'收货地址不能为空'
			})
			return;
		}
		save({"goodsId":infoObj.value.id,"quantity":quantity.value,"productSpecificationsIds":productSpecificationsIds.value.join(','),
		"totalPrice":infoObj.value.price*quantity.value,"unitPrice":infoObj.value.price,"receivingAddressId":myaddress.value.id});
		getCartNum(infoObj.value.id)
		let params={
					type: 'success',
					title: '默认主题',
					message: "加入购物车成功"
				}
		toast.value.show({
			...params,
			complete() {
				close()
			}
		})
	}
}
const nickname=ref("小妮子")
if(nickname.value.length >= 3){
	nickname.value = nickname.value.substring(0,1)+"**"+nickname.value.substring(nickname.value.length-1)
}
const popupComment=ref()
const openComment=()=>{
	popupComment.value.open('bottom')
}
const commentbtns=ref([
	{
		text:'全部',
	},
	{
		text:'好评',
	},
	{
		text:'差评',
	},
	{
		text:'图/视频',
	}
])
const currentCommentIndex=ref(-1)
const selectCommentButton=(index)=>{
	currentCommentIndex.value=index
	queryParamsComment.value.commentStatus=index
	queryParamsComment.value.page=1
	getComment(currentGoodsId.value)
}
const myaddress=ref()
const getDefaultAddress=()=>{
	pageReceive({"defaulted":'1'}).then(res=>{
		if(res.data.list.length > 0){
			myaddress.value=res.data.list[0]
		}
	})
}
const style=ref({
	img: 'width: 98%',
})
</script>

<template>
  <view class="container-goods" v-if="infoObj">
    <view class="header">
      <swiper  style="z-index: 0;" class="swiper" circular :indicator-dots="true" :autoplay="false" :interval="2000"
              :duration="500">
        <swiper-item v-for="(item,index) in infoObj.childImages.split(',')">
          <view class="swiper-item"><image :src="baseUrl+item" style="width: 100%;height: 100%;border-radius: 3px;"></image></view>
        </swiper-item>
      </swiper>
    </view>
    <view class="content">
      <view class="goodname">
        <text style="font-weight: bolder;font-size: 16px;">{{infoObj.goodsName}}</text>
        <text>{{infoObj.price}}元/{{infoObj.unitName}}</text>
      </view>
      <view class="detail">
        <text>{{infoObj.detailIntroduce}}</text>
      </view>
      <view class="quantity">
        已售：{{infoObj.selledQuantity ? infoObj.selledQuantity:0}}
      </view>
	  <view style="padding-bottom: 5px;">
		  <view  class="commentlist" @click="openComment">
			  <text style="font-size: 16px;font-size: 14px;">评价({{commenttotal}})</text>
			  <view>
			  			  <text style="color: gray;font-size: 14px;">
			  			  			  查看全部
			  			  </text>
			  			  <uni-icons type="right" color="lightgray"></uni-icons>
			  </view>
		  </view>
		  <view style="margin-top: 10px;padding-right: 5px;"  @click="openComment">
			  <view style="display: flex;flex-direction: row;justify-content: space-between;margin-bottom: 10px;" v-for="(item,index) in comments">
				  <view   style="display: flex;flex-direction: column;margin-right: 5px;"  v-if="index < 2">
					  <view  style="display: flex;flex-direction: row;align-items: center;">
						  <uv-avatar :src="baseUrl+item.avatar"  size="30"></uv-avatar>
						  <text style="margin-left:5px;margin-right: 5px;font-weight: 550;">{{item.nickName}}</text>
						  <text style="color: gray;">口味:麻辣味250克</text>
					  </view>
					  <text style="padding-left: 2rem;margin-top: 5px;display: -webkit-box;-webkit-line-clamp: 3;
					  -webkit-box-orient: vertical;overflow: hidden;">{{item.commentContent}}</text>
				  </view>
				   <image  v-if="index < 2 && item.commentPicturesFirst" :src="baseUrl+item.commentPicturesFirst" style="width: 100px; height: 100px;border-radius: 5px;"></image>
			  </view>
		  </view>
	  </view>
    </view>
    <view class="detailcontenttitle">
      详情
    </view>
	<view class="detailcontent">
      <!-- <rich-text id="deschtml" v-html="infoObj.descHtml"></rich-text> -->
	  <uv-parse :content="infoObj.descHtml" :tagStyle="style"></uv-parse>
    </view>
    <view class="goods-carts">
      <uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
                     @buttonClick="buttonClick" />
    </view>
	<uv-popup ref="popupComment">
		<view class="status-order">
			<view :key="index"  v-for="(item,index) in commentbtns"
			style="margin-left: 8px;">
				<uv-tags  plain  :text="item.text"
				:color="currentCommentIndex == -1 ? 'black': index === currentCommentIndex ? 'orangered':'black'"
				:bgColor="currentCommentIndex == -1 ? '#ffffff': index === currentCommentIndex ? ' #ffedd2;':'#ffffff'" 
				 :borderColor="currentCommentIndex == -1 ? '#ffffff': index === currentCommentIndex ? ' #ffedd2;':'#ffffff'" 
				@click="selectCommentButton(index)"
				></uv-tags>
			</view>
		</view>
		<view class="comment-page">
			<view class="comment-content">
				<view v-if="comments.length>0" class="comment-info" v-for="(item,index) in comments">
					<uv-avatar :src="baseUrl+item.avatar" size="30"></uv-avatar>
					<view style="margin-left: 5px;width: 85%;">
						<view class="comment-title">
							<text style="margin-right: 5px;">{{item.nickName}}</text>
							<uni-icons type="more" size="30"></uni-icons>
						</view>
						<view class="comment-1">
							<view style="display: flex;flex-direction: row;align-items: center;">
								<uni-icons color="orangered" type="heart" size="20"></uni-icons>
								<text style="color: orangered;">超赞</text>
								<text style="color: gray;">&nbsp;|&nbsp;</text>
								<text style="color: gray;">已购 2斤</text>
							</view>
							<text style="color: gray;">1周前</text>
						</view>
						<view>
							{{item.commentContent}}
						</view>
						<view class="comment-img">
							<!-- <video src="/src/static/logo.png" style="width: 100px; height: 100px;border-radius: 5px;"></video> -->
							<image   v-if="item.commentPictures" 
							v-for="(img,indeximg) in item.commentPictures.split(',')" 
							:src="baseUrl+img" style="width: 100px; height: 100px;border-radius: 5px;"></image>
						</view>
					</view>
				</view>
				<uv-empty v-else></uv-empty>
			</view>
			<view class="goods-carts">
			  <uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
			                 @buttonClick="buttonClick" />
			</view>
		</view>
	</uv-popup>
	<uv-toast ref="toast"></uv-toast>
    <uni-popup ref="popup" background-color="#fff" @change="change" style="z-index: 1;">
	  <view class="popup-content">
		<view class="useraddress"  v-if="myaddress">
		  <view style="display: flex;
align-items: center;width: 70%;">
			<uni-icons type="location" size="20"></uni-icons> <text>{{myaddress.address}}{{myaddress.detailAddress}} {{myaddress.name}} {{myaddress.phone}}</text>
		  </view>
		  <view style="text-align: right;width: 30%;display: flex;align-items: center;">
			<text style="color: darkgray;">默认</text><button @click="goToReceivingAddress" type="default" style="border: none;padding-left: 5px;padding-right: 5px;" size="mini">选择</button>
		  </view>
		</view>
		<view  v-if="!myaddress"  class="useraddress" style="justify-content: space-between;">
						 <text  style="color: darkgray;width: 80%;">请填写收货地址</text>
						 <button @click="goToReceivingAddress" type="primary" style="border: none;padding-left: 5px;padding-right: 5px;" size="mini">选择</button>
		</view>
		<view class="infos">
		  <image :src="infoObj.mainImage" class="image"></image>
		  <view class="info">
			<view style="margin-bottom: 5px;display: flex;justify-content: space-between;">
				 <text style="font-size: 16px;font-weight: bold;">{{infoObj.goodsName}}</text>
				 <text style="font-size: 14px;">价格：{{infoObj.price*quantity}}</text>
			</view>
			<view style="display: flex;justify-content: space-between;font-size: 14px;">
			  <text>单价：{{infoObj.price}}元</text>
			  <text>剩余数量：{{infoObj.supplyQuantity ? infoObj.supplyQuantity:0}}</text>
			</view>
			  <view>
				<uni-number-box  :min="1" :max="12" :value="quantity" v-model="quantity"/>
			  </view>
		  </view>
		</view>
		<view class="choose">
		  <view style="padding: 5px;font-size: 14px;" v-if="infoObj.weights.length>0">
			   <view>
				   重量
			   </view>
			   <view style="margin-top: 5px;">
				   <button style="margin-right: 5px;" size="mini" v-for="(item,index) in infoObj.weights"
				   :key="index" :class="{'active':index === currentIndex}" @click="selectButton(item.id,index)">{{item.weight}}{{item.weightUnitName}} {{item.price}}元</button>
			   </view>
		  </view>
		  <view style="padding: 5px;font-size: 14px;" v-if="infoObj.sizes.length>0">
			   <view>
				尺寸
			   </view>
			   <view style="margin-top: 5px;">
				   <span  v-for="(item,index) in infoObj.sizes"
				   :key="index">
				   <button v-if="item.sizeName"   style="margin-right: 5px;" size="mini" :class="{'activeSize':index === currentIndexSize}" @click="selectButtonSize(item.id,index)">{{item.sizeName}}</button>
				   </span>
				   
			   </view>
		  </view>
		  <view  style="padding: 5px;font-size: 14px;"   v-if="infoObj.colorClassicList.length>0">
			   <view>颜色分类</view>
			   <view  style="margin-top: 5px;" v-for="(item,index) in infoObj.colorClassicList">
				   <button style="margin-right: 5px;" size="mini" 
				   :key="index" :class="{'activeColorClassic':index === currentIndexColorClassic}" @click="selectButtonColorClassic(item.id,index)">
					 {{item.color}} {{item.goodsSubName}} 【{{item.style}}】{{item.additional}} {{item.remark}}
				   </button>
			   </view>
		  </view>
		  <view class="uni-btn">
			<button type="primary" plain size="mini" style="margin-right: 20px" @click="sumitBtn">{{sumitText}}</button>
			<button type="info" plain size="mini" @click="close">取消</button>
		  </view>
		</view>
	  </view>
	</uni-popup>
	<loginDialog></loginDialog>
  </view>
</template>

<style scoped lang="scss">
	.comment-img{
	  display: grid; 
	  grid-template-columns: repeat(3, 1fr);
	  gap: 1px;
	  justify-content: center;
	  align-items: center;
	  width: 100%;
	  margin-top: 10px;
	}
	.comment-1{
		display: flex;flex-direction: row;align-items: center;justify-content: space-between;
		margin-bottom: 8px;
		margin-top: 4px;
		width: 100%;
	}
	.comment-title{
		display: flex;justify-content: space-between;align-items: center;
		width: 100%;
	}
	.comment-info{
		display: flex;flex-direction: row;justify-content: left;
		width: 100%;
		margin-bottom: 10px;
		border-bottom:1px solid gainsboro;
		border-top:1px solid ghostwhite;
		padding-top: 10px;
		padding-bottom: 10px;
	}
	.comment-content{
		overflow: auto;
		width: 100%;
		margin-top: 20%;
		margin-left: 5px;
		margin-right: 5px;
		margin-bottom: 10px;
		height: 90%;
	}
	.status-order{
		height: 10%;
		display: flex;
		align-items: center;
		justify-content: left;
		width: 100%;
		position: absolute;
		top:0;
		background-color: whitesmoke;
		padding-top: 10px;
		padding-bottom: 10px;
		margin-top: 0px;
	}
.comment-page{
	height: 80vh;
	width: 100%;
	position: relative;
}
.shopping-info{
	display: flex;
	flex-direction: column;
}	
.active{
	color: orangered;
	border:1px solid orangered;
}	
.activeSize{
	color: orangered;
	border:1px solid orangered;
}	
.activeColorClassic{
	color: orangered;
	border:1px solid orangered;
}
.useraddress{
  padding-bottom: 10px;
  height: 10%;
  width: 100%;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.uni-btn{
  padding: 10px;
  width: 100%;
  text-align: center;
  position: sticky;
  bottom: 0;
  background-color: #fff;
}
.info{
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  width: 75%;
  height: 100%;
}
.image{
  width: 25%;height: 80px;border-radius: 5px;
}
.infos{
  display: inline-flex;
  height: 70%;
  width:100%;
}
.choose{
  width: 100%;
  height: auto;
  position: relative;
  overflow-y: auto;
}
.choose::-webkit-scrollbar{
	display: none;
}
.popup-content {
  padding: 20px;
  max-height: 60vh;
  height: auto;
  overflow: auto;
}
.goods-carts {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
  position: fixed;
  left: 0;
  right: 0;
  /* #ifdef H5 */
  left: var(--window-left);
  right: var(--window-right);
  /* #endif */
  bottom: 0;
}
.detailcontent{
  margin-top: 3%;
  height: 80%;
  width: 100%;
  padding: 5px;
}
.content{
  padding: 10rpx;
}
.goodname{
  display: flex;
  justify-content: space-between;
  padding-right: 10px;
  align-items: center;
  padding-bottom: 5px;
}
.commentlist{
  display: flex;
  justify-content: space-between;
  padding-right: 5px;
  align-items: center;
  padding-bottom: 5px;
  padding-top: 5px;
}
.detail{
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  font-size: 14px;
}
.detailcontenttitle{
  height: auto;
  display: flex;
  align-items: center;
  margin-left: 4px;
  color: gray;
  font-size: 14px;
}
.quantity{
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  font-size: 14px;
}
.container-goods{
  width: 100%;
  height: 90vh;
}
.header{
  height: 80%;
  width: 100%;
}
.swiper {
  height: 100%;
  width: 100%;
}
.swiper-item {
  display: block;
  height:100%;
  line-height: 300rpx;
  text-align: center;
  padding: 2px;
}
</style>